package com.jt.provider.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

@RefreshScope
@RestController
public class ProviderCacheController {

    @Value("${useLocalCache:false}")
    private boolean useLocalCache;

    @RequestMapping("/provider/cache")
    public String doUseLocalCache() {
        return "useLocalCache value is " + useLocalCache;
    }

    //---------------------------------------
    //构建一个本地(Local)缓存对象(基于jvm中的一个对象存储从数据库获取的数据)
    private List<String> cache = new CopyOnWriteArrayList<>();

    @RequestMapping("/provider/cache02")
    public List<String> doUseLocalCache02() {
        System.out.println("本地缓存是否已经开启: " + useLocalCache);
        if (!useLocalCache) { //未开启本地缓存
            System.out.println("==Get data from database==");
            return Arrays.asList("a","b","c");
        }
        if (cache.isEmpty()) {
            synchronized (cache) { // Thread-A Thread-B
                if (cache.isEmpty()) {
                    System.out.println("==Get data from database==");
                    // 模拟数据库获取的数据
                    List<String> cates = Arrays.asList("a","b","c");
                    cache.addAll(cates);
                }
            }
        }
        return cache;
    } // 生产层面
}
